<?php

namespace app\services;

use plugin\admin\app\model\Link;
use plugin\admin\app\model\LinkCategory;

class LinkService
{
    /**
     * Get link categories and their associated links.
     *
     * @return array
     */
    public function getCategoriesWithLinks(): array
    {
        // Fetch all categories
        $categories = LinkCategory::all()->keyBy('id');

        // Fetch all links
        $links = Link::all(['id', 'name', 'en_name', 'link', 'h5_link', 'is_ext', 'category_id', 'is_action', 'action']);

        $currentLanguage = get_current_language();

        // Group links by category_id
        $groupedLinks = $links->groupBy('category_id');

        // Assemble the result
        $result = $categories->map(function ($category) use ($groupedLinks, $currentLanguage) {
            $links = $groupedLinks->get($category->id, collect())->map(function ($link) use ($currentLanguage) {
                if ($currentLanguage === 'en') {
                    $link->name = $link->en_name;
                }

                if ($link->id == 4) {
                    $link->link = build_edit_tools_url('create');
                }

                return $link;
            });

            return [
                'id' => $category->id,
                'name' => get_current_language() == 'en' ? $category->en_name : $category->name,
                'links' => $links->toArray(),
            ];
        })->values()->toArray();

        return $result;
    }
}